<template>
  <div>
    <el-dropdown trigger = "click" @command = "handleSize">
      <div>
        <svg-icon class-name = "size-icon" icon-class = "size"></svg-icon>
      </div>
      <template #dropdown>
        <el-dropdown-menu>
          <el-dropdown-item
              v-for = "item in sizeOptions"
              :key = "item.value"
              :command = "item.value"
              :disabled = "item.value === size"
          >
            {{ item.label }}
          </el-dropdown-item>
        </el-dropdown-menu>
      </template>
    </el-dropdown>
  </div>
</template>

<script lang = "ts">
import { computed, defineComponent, getCurrentInstance, reactive, nextTick } from 'vue'
import { useStore } from '../../store'
import { useRoute, useRouter } from 'vue-router'
import { Size } from '@/plugins/element'
import { CHANGE_SIZE, CLEAR_CACHE_VIEW } from '@/store/modules/methods-type'

export default defineComponent({
  name: 'SizeSelect',
  setup() {
    const store = useStore(),
        route = useRoute(),
        router = useRouter(),
        { proxy } = getCurrentInstance()!,
        size = computed(() => store.getters.size),
        sizeOptions = reactive([
          { label: 'Default', value: 'default' },
          { label: 'Medium', value: 'medium' },
          { label: 'Small', value: 'small' },
          { label: 'Mini', value: 'mini' }
        ])

    /* 刷新当前路由 */
    const refreshView = () => {
      store.dispatch(`tagsView/${CLEAR_CACHE_VIEW}`)
      const { fullPath } = route
      nextTick(() => {
        /* 重定向到中间页 实现路由刷新 */
        router.replace({ path: `/redirect${ fullPath }` })
      })
    }

    /* 获取点击按钮的command属性值 作为size的值 */
    const handleSize = (command: Size) => {
      /* 修改组件的默认尺寸 */
      proxy!.$ELEMENT.size = command
      store.dispatch(`app/${ CHANGE_SIZE }`, command)
      /* 切换size的时候 只有刷新路由才有效果 */
      refreshView()
      proxy!.$message.success({ type: 'success', message: 'Switch Size Success' })
    }

    return {
      sizeOptions,
      size,
      handleSize
    }
  }
})
</script>

<style lang = "scss">
.size-icon {
  font-size: 18px;
}
</style>
